home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / bash_114.zip / bash-1.14.2 / general.c < prev    next >
C/C++ Source or Header  |  1994-07-26  |  27KB  |  1,214 lines

  1. /* general.c -- Stuff that is used by all files. */
  2.  
  3. /* Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992
  4.    Free Software Foundation, Inc.
  5.  
  6.    This file is part of GNU Bash, the Bourne Again SHell.
  7.  
  8.    Bash is free software; you can redistribute it and/or modify it under
  9.    the terms of the GNU General Public License as published by the Free
  10.    Software Foundation; either version 2, or (at your option) any later
  11.    version.
  12.  
  13.    Bash is distributed in the hope that it will be useful, but WITHOUT ANY
  14.    WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15.    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  16.    for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License along
  19.    with Bash; see the file COPYING.  If not, write to the Free Software
  20.    Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  21.  
  22. #include "config.h"    /* includes unistd.h for us */
  23. #include <stdio.h>
  24. #include <ctype.h>
  25. #include <errno.h>
  26. #include "bashtypes.h"
  27. #include <sys/param.h>
  28. #if defined (_POSIX_VERSION)
  29. #  if defined (amiga) && defined (USGr4)
  30. #    define _POSIX_SOURCE
  31. #  endif
  32. #  include <signal.h>
  33. #  if defined (amiga) && defined (USGr4)
  34. #    undef _POSIX_SOURCE
  35. #  endif
  36. #endif /* _POSIX_VERSION */
  37. #include "filecntl.h"
  38. #include "bashansi.h"
  39. #include "shell.h"
  40. #include <tilde/tilde.h>
  41.  
  42. #if !defined (USG) || defined (HAVE_RESOURCE)
  43. #  include <sys/time.h>
  44. #endif
  45.  
  46. #include <sys/times.h>
  47. #include "maxpath.h"
  48.  
  49. #if !defined (errno)
  50. extern int errno;
  51. #endif /* !errno */
  52.  
  53. /* Make the functions strchr and strrchr if they do not exist. */
  54. #if !defined (HAVE_STRCHR)
  55. char *
  56. strchr (string, c)
  57.      char *string;
  58.      int c;
  59. {
  60.   register int i;
  61.  
  62.   for (i = 0; string && string[i]; i++)
  63.     if (string[i] == c)
  64.       return ((char *) (string + i));
  65.  
  66.   return ((char *) NULL);
  67. }
  68.  
  69. char *
  70. strrchr (string, c)
  71.      char *string;
  72.      int c;
  73. {
  74.   register int i;
  75.  
  76.   if (string)
  77.     i = strlen (string) - 1;
  78.   else
  79.     i = -1;
  80.  
  81.   for (; string && i > -1; i--)
  82.     if (string[i] == c)
  83.       return ((char *) (string + i));
  84.  
  85.   return ((char *) NULL);
  86. }
  87. #endif /* !HAVE_STRCHR */
  88.  
  89. /* **************************************************************** */
  90. /*                                    */
  91. /*           Memory Allocation and Deallocation.            */
  92. /*                                    */
  93. /* **************************************************************** */
  94.  
  95. char *
  96. xmalloc (size)
  97.      int size;
  98. {
  99.   register char *temp = (char *)malloc (size);
  100.  
  101.   if (!temp)
  102.     fatal_error ("Out of virtual memory!");
  103.  
  104.   return (temp);
  105. }
  106.  
  107. char *
  108. xrealloc (pointer, size)
  109.      GENPTR pointer;
  110.      int size;
  111. {
  112.   char *temp;
  113.  
  114.   if (!pointer)
  115.     temp = xmalloc (size);
  116.   else
  117.     temp = (char *)realloc (pointer, size);
  118.  
  119.   if (!temp)
  120.     fatal_error ("Out of virtual memory!");
  121.  
  122.   return (temp);
  123. }
  124.  
  125. /* Use this as the function to call when adding unwind protects so we
  126.    don't need to know what free() returns. */
  127. void
  128. xfree (string)
  129.      char *string;
  130. {
  131.   free (string);
  132. }
  133.  
  134. /* **************************************************************** */
  135. /*                                    */
  136. /*             Integer to String Conversion            */
  137. /*                                    */
  138. /* **************************************************************** */
  139.  
  140. /* Number of characters that can appear in a string representation
  141.    of an integer.  32 is larger than the string rep of 2^^31 - 1. */
  142. #define MAX_INT_LEN 32
  143.  
  144. /* Integer to string conversion.  This conses the string; the
  145.    caller should free it. */
  146. char *
  147. itos (i)
  148.      int i;
  149. {
  150.   char *buf, *p, *ret;
  151.   int negative = 0;
  152.   unsigned int ui;
  153.  
  154.   buf = xmalloc (MAX_INT_LEN);
  155.  
  156.   if (i < 0)
  157.     {
  158.       negative++;
  159.       i = -i;
  160.     }
  161.  
  162.   ui = (unsigned int) i;
  163.  
  164.   buf[MAX_INT_LEN - 1] = '\0';
  165.   p = &buf[MAX_INT_LEN - 2];
  166.  
  167.   do
  168.     *p-- = (ui % 10) + '0';
  169.   while (ui /= 10);
  170.  
  171.   if (negative)
  172.     *p-- = '-';
  173.  
  174.   ret = savestring (p + 1);
  175.   free (buf);
  176.   return (ret);
  177. }
  178.  
  179. /* Return non-zero if all of the characters in STRING are digits. */
  180. int
  181. all_digits (string)
  182.      char *string;
  183. {
  184.   while (*string)
  185.     {
  186.       if (!digit (*string))
  187.     return (0);
  188.       else
  189.     string++;
  190.     }
  191.   return (1);
  192. }
  193.  
  194. /* atol(3) is not universal */
  195. long
  196. string_to_long (s)
  197.      char *s;
  198. {
  199.   long ret = 0L;
  200.   int neg = 0;
  201.  
  202.   while (s && *s && whitespace (*s))
  203.     s++;
  204.   if (*s == '-' || *s == '+')
  205.     {
  206.       neg = *s == '-';
  207.       s++;
  208.     }
  209.   for ( ; s && *s && digit (*s); s++)
  210.     ret = (ret * 10) + digit_value (*s);
  211.   return (neg ? -ret : ret);
  212. }
  213.  
  214. /* Return 1 if this token is a legal shell `identifier'; that is, it consists
  215.    solely of letters, digits, and underscores, and does not begin with a
  216.    digit. */
  217. int
  218. legal_identifier (name)
  219.      char *name;
  220. {
  221.   register char *s;
  222.  
  223.   if (!name || !*name || digit (*name))
  224.     return (0);
  225.  
  226.   for (s = name; s && *s; s++)
  227.     {
  228.       if (!isletter (*s) && !digit (*s) && (*s != '_'))
  229.         return (0);
  230.     }
  231.   return (1);
  232. }
  233.  
  234. /* Make sure that WORD is a valid shell identifier, i.e.
  235.    does not contain a dollar sign, nor is quoted in any way.  Nor
  236.    does it consist of all digits.  If CHECK_WORD is non-zero,
  237.    the word is checked to ensure that it consists of only letters,
  238.    digits, and underscores. */
  239. check_identifier (word, check_word)
  240.      WORD_DESC *word;
  241.      int check_word;
  242. {
  243.   if (word->dollar_present || word->quoted || all_digits (word->word))
  244.     {
  245.       report_error ("`%s' is not a valid identifier", word->word);
  246.       return (0);
  247.     }
  248.   else if (check_word && legal_identifier (word->word) == 0)
  249.     {
  250.       report_error ("`%s' is not a valid identifier", word->word);
  251.       return (0);
  252.     }
  253.   else
  254.     return (1);
  255. }
  256.  
  257. /* A function to unset no-delay mode on a file descriptor.  Used in shell.c
  258.    to unset it on the fd passed as stdin.  Should be called on stdin if
  259.    readline gets an EAGAIN or EWOULDBLOCK when trying to read input. */
  260.  
  261. #if !defined (O_NDELAY)
  262. #  if defined (FNDELAY)
  263. #    define O_NDELAY FNDELAY
  264. #  endif
  265. #endif /* O_NDELAY */
  266.  
  267. /* Make sure no-delay mode is not set on file descriptor FD. */
  268. void
  269. unset_nodelay_mode (fd)
  270.      int fd;
  271. {
  272.   int flags, set = 0;
  273.  
  274.   if ((flags = fcntl (fd, F_GETFL, 0)) < 0)
  275.     return;
  276.  
  277. #if defined (O_NONBLOCK)
  278.   if (flags & O_NONBLOCK)
  279.     {
  280.       flags &= ~O_NONBLOCK;
  281.       set++;
  282.     }
  283. #endif /* O_NONBLOCK */
  284.  
  285. #if defined (O_NDELAY)
  286.   if (flags & O_NDELAY)
  287.     {
  288.       flags &= ~O_NDELAY;
  289.       set++;
  290.     }
  291. #endif /* O_NDELAY */
  292.  
  293.   if (set)
  294.     fcntl (fd, F_SETFL, flags);
  295. }
  296.  
  297.  
  298. /* **************************************************************** */
  299. /*                                    */
  300. /*            Generic List Functions                */
  301. /*                                    */
  302. /* **************************************************************** */
  303.  
  304. /* Call FUNCTION on every member of LIST, a generic list. */
  305. void
  306. map_over_list (list, function)
  307.      GENERIC_LIST *list;
  308.      Function *function;
  309. {
  310.   while (list)
  311.     {
  312.       (*function) (list);
  313.       list = list->next;
  314.     }
  315. }
  316.  
  317. /* Call FUNCTION on every string in WORDS. */
  318. void
  319. map_over_words (words, function)
  320.      WORD_LIST *words;
  321.      Function *function;
  322. {
  323.   while (words)
  324.     {
  325.       (*function)(words->word->word);
  326.       words = words->next;
  327.     }
  328. }
  329.  
  330. /* Reverse the chain of structures in LIST.  Output the new head
  331.    of the chain.  You should always assign the output value of this
  332.    function to something, or you will lose the chain. */
  333. GENERIC_LIST *
  334. reverse_list (list)
  335.      GENERIC_LIST *list;
  336. {
  337.   register GENERIC_LIST *next, *prev = (GENERIC_LIST *)NULL;
  338.  
  339.   while (list)
  340.     {
  341.       next = list->next;
  342.       list->next = prev;
  343.       prev = list;
  344.       list = next;
  345.     }
  346.   return (prev);
  347. }
  348.  
  349. /* Return the number of elements in LIST, a generic list. */
  350. int
  351. list_length (list)
  352.      GENERIC_LIST *list;
  353. {
  354.   register int i;
  355.  
  356.   for (i = 0; list; list = list->next, i++);
  357.   return (i);
  358. }
  359.  
  360. /* A global variable which acts as a sentinel for an `error' list return. */
  361. GENERIC_LIST global_error_list;
  362.  
  363. /* Delete the element of LIST which satisfies the predicate function COMPARER.
  364.    Returns the element that was deleted, so you can dispose of it, or -1 if
  365.    the element wasn't found.  COMPARER is called with the list element and
  366.    then ARG.  Note that LIST contains the address of a variable which points
  367.    to the list.  You might call this function like this:
  368.  
  369.    SHELL_VAR *elt = delete_element (&variable_list, check_var_has_name, "foo");
  370.    dispose_variable (elt);
  371. */
  372. GENERIC_LIST *
  373. delete_element (list, comparer, arg)
  374.      GENERIC_LIST **list;
  375.      Function *comparer;
  376.      char *arg;
  377. {
  378.   register GENERIC_LIST *prev = (GENERIC_LIST *)NULL;
  379.   register GENERIC_LIST *temp = *list;
  380.  
  381.   while (temp)
  382.     {
  383.       if ((*comparer) (temp, arg))
  384.     {
  385.       if (prev)
  386.         prev->next = temp->next;
  387.       else
  388.         *list = temp->next;
  389.       return (temp);
  390.     }
  391.       prev = temp;
  392.       temp = temp->next;
  393.     }
  394.   return ((GENERIC_LIST *)&global_error_list);
  395. }
  396.  
  397. /* Find NAME in ARRAY.  Return the index of NAME, or -1 if not present.
  398.    ARRAY should be NULL terminated. */
  399. int
  400. find_name_in_list (name, array)
  401.      char *name, **array;
  402. {
  403.   int i;
  404.  
  405.   for (i = 0; array[i]; i++)
  406.     if (strcmp (name, array[i]) == 0)
  407.       return (i);
  408.  
  409.   return (-1);
  410. }
  411.  
  412. /* Return the length of ARRAY, a NULL terminated array of char *. */
  413. int
  414. array_len (array)
  415.      char **array;
  416. {
  417.   register int i;
  418.   for (i = 0; array[i]; i++);
  419.   return (i);
  420. }
  421.  
  422. /* Free the contents of ARRAY, a NULL terminated array of char *. */
  423. void
  424. free_array (array)
  425.      char **array;
  426. {
  427.   register int i = 0;
  428.  
  429.   if (!array) return;
  430.  
  431.   while (array[i])
  432.     free (array[i++]);
  433.   free (array);
  434. }
  435.  
  436. /* Allocate and return a new copy of ARRAY and its contents. */
  437. char **
  438. copy_array (array)
  439.      char **array;
  440. {
  441.   register int i;
  442.   int len;
  443.   char **new_array;
  444.  
  445.   len = array_len (array);
  446.  
  447.   new_array = (char **)xmalloc ((len + 1) * sizeof (char *));
  448.   for (i = 0; array[i]; i++)
  449.     new_array[i] = savestring (array[i]);
  450.   new_array[i] = (char *)NULL;
  451.  
  452.   return (new_array);
  453. }
  454.  
  455. /* Comparison routine for use with qsort() on arrays of strings. */
  456. int
  457. qsort_string_compare (s1, s2)
  458.      register char **s1, **s2;
  459. {
  460.   int result;
  461.  
  462.   if ((result = **s1 - **s2) == 0)
  463.     result = strcmp (*s1, *s2);
  464.  
  465.   return (result);
  466. }
  467.  
  468. /* Append LIST2 to LIST1.  Return the header of the list. */
  469. GENERIC_LIST *
  470. list_append (head, tail)
  471.      GENERIC_LIST *head, *tail;
  472. {
  473.   register GENERIC_LIST *t_head = head;
  474.  
  475.   if (!t_head)
  476.     return (tail);
  477.  
  478.   while (t_head->next)
  479.     t_head = t_head->next;
  480.   t_head->next = tail;
  481.   return (head);
  482. }
  483.  
  484. /* Some random string stuff. */
  485.  
  486. /* Remove all leading whitespace from STRING.  This includes
  487.    newlines.  STRING should be terminated with a zero. */
  488. void
  489. strip_leading (string)
  490.      char *string;
  491. {
  492.   char *start = string;
  493.  
  494.   while (*string && (whitespace (*string) || *string == '\n'))
  495.     string++;
  496.  
  497.   if (string != start)
  498.     {
  499.       int len = strlen (string);
  500.       FASTCOPY (string, start, len);
  501.       start[len] = '\0';
  502.     }
  503. }
  504.  
  505. /* Remove all trailing whitespace from STRING.  This includes
  506.    newlines.  If NEWLINES_ONLY is non-zero, only trailing newlines
  507.    are removed.  STRING should be terminated with a zero. */
  508. void
  509. strip_trailing (string, newlines_only)
  510.      char *string;
  511.      int newlines_only;
  512. {
  513.   int len = strlen (string) - 1;
  514.  
  515.   while (len >= 0)
  516.     {
  517.       if ((newlines_only && string[len] == '\n') ||
  518.           (!newlines_only && whitespace (string[len])))
  519.         len--;
  520.       else
  521.         break;
  522.     }
  523.   string[len + 1] = '\0';
  524. }
  525.  
  526. /* Canonicalize PATH, and return a new path.  The new path differs from PATH
  527.    in that:
  528.     Multple `/'s are collapsed to a single `/'.
  529.     Leading `./'s and trailing `/.'s are removed.
  530.     Trailing `/'s are removed.
  531.     Non-leading `../'s and trailing `..'s are handled by removing
  532.     portions of the path. */
  533. char *
  534. canonicalize_pathname (path)
  535.      char *path;
  536. {
  537.   register int i, start;
  538.   char stub_char;
  539.   char *result;
  540.  
  541.   /* The result cannot be larger than the input PATH. */
  542.   result = savestring (path);
  543.  
  544.   stub_char = (*path == '/') ? '/' : '.';
  545.  
  546.   /* Walk along RESULT looking for things to compact. */
  547.   i = 0;
  548.   while (1)
  549.     {
  550.       if (!result[i])
  551.     break;
  552.  
  553.       while (result[i] && result[i] != '/')
  554.     i++;
  555.  
  556.       start = i++;
  557.  
  558.       /* If we didn't find any slashes, then there is nothing left to do. */
  559.       if (!result[start])
  560.     break;
  561.  
  562.       /* Handle multiple `/'s in a row. */
  563.       while (result[i] == '/')
  564.     i++;
  565.  
  566. #if !defined (apollo)
  567.       if ((start + 1) != i)
  568. #else
  569.       if ((start + 1) != i && (start != 0 || i != 2))
  570. #endif /* apollo */
  571.     {
  572.       strcpy (result + start + 1, result + i);
  573.       i = start + 1;
  574.     }
  575.  
  576.       /* Handle backquoted `/'. */
  577.       if (start > 0 && result[start - 1] == '\\')
  578.     continue;
  579.  
  580.       /* Check for trailing `/'. */
  581.       if (start && !result[i])
  582.     {
  583.     zero_last:
  584.       result[--i] = '\0';
  585.       break;
  586.     }
  587.  
  588.       /* Check for `../', `./' or trailing `.' by itself. */
  589.       if (result[i] == '.')
  590.     {
  591.       /* Handle trailing `.' by itself. */
  592.       if (!result[i + 1])
  593.         goto zero_last;
  594.  
  595.       /* Handle `./'. */
  596.       if (result[i + 1] == '/')
  597.         {
  598.           strcpy (result + i, result + i + 1);
  599.           i = start;
  600.           continue;
  601.         }
  602.  
  603.       /* Handle `../' or trailing `..' by itself. */
  604.       if (result[i + 1] == '.' &&
  605.           (result[i + 2] == '/' || !result[i + 2]))
  606.         {
  607.           while (--start > -1 && result[start] != '/');
  608.           strcpy (result + start + 1, result + i + 2);
  609.           i = start;
  610.           continue;
  611.         }
  612.     }
  613.     }
  614.  
  615.   if (!*result)
  616.     {
  617.       *result = stub_char;
  618.       result[1] = '\0';
  619.     }
  620.   return (result);
  621. }
  622.  
  623. /* Turn STRING (a pathname) into an absolute pathname, assuming that
  624.    DOT_PATH contains the symbolic location of `.'.  This always
  625.    returns a new string, even if STRING was an absolute pathname to
  626.    begin with. */
  627. char *
  628. make_absolute (string, dot_path)
  629.      char *string, *dot_path;
  630. {
  631.   char *result;
  632.   int result_len;
  633.   
  634.   if (!dot_path || *string == '/')
  635.     result = savestring (string);
  636.   else
  637.     {
  638.       if (dot_path && dot_path[0])
  639.     {
  640.       result = xmalloc (2 + strlen (dot_path) + strlen (string));
  641.       strcpy (result, dot_path);
  642.       result_len = strlen (result);
  643.       if (result[result_len - 1] != '/')
  644.         {
  645.           result[result_len++] = '/';
  646.           result[result_len] = '\0';
  647.         }
  648.     }
  649.       else
  650.     {
  651.       result = xmalloc (3 + strlen (string));
  652.       result[0] = '.'; result[1] = '/'; result[2] = '\0';
  653.       result_len = 2;
  654.     }
  655.  
  656.       strcpy (result + result_len, string);
  657.     }
  658.  
  659.   return (result);
  660. }
  661.  
  662. /* Return 1 if STRING contains an absolute pathname, else 0. */
  663. int
  664. absolute_pathname (string)
  665.      char *string;
  666. {
  667.   if (!string || !*string)
  668.     return (0);
  669.  
  670.   if (*string == '/')
  671.     return (1);
  672.  
  673.   if (*string++ == '.')
  674.     {
  675.       if (!*string || *string == '/')
  676.     return (1);
  677.  
  678.       if (*string == '.' && (string[1] == '\0' || string[1] == '/'))
  679.     return (1);
  680.     }
  681.   return (0);
  682. }
  683.  
  684. /* Return 1 if STRING is an absolute program name; it is absolute if it
  685.    contains any slashes.  This is used to decide whether or not to look
  686.    up through $PATH. */
  687. int
  688. absolute_program (string)
  689.      char *string;
  690. {
  691.   return ((char *)strchr (string, '/') != (char *)NULL);
  692. }
  693.  
  694. /* Return the `basename' of the pathname in STRING (the stuff after the
  695.    last '/').  If STRING is not a full pathname, simply return it. */
  696. char *
  697. base_pathname (string)
  698.      char *string;
  699. {
  700.   char *p;
  701.  
  702.   if (!absolute_pathname (string))
  703.     return (string);
  704.  
  705.   p = (char *)strrchr (string, '/');
  706.   if (p)
  707.     return (++p);
  708.   else
  709.     return (string);
  710. }
  711.  
  712. /* Return the full pathname of FILE.  Easy.  Filenames that begin
  713.    with a '/' are returned as themselves.  Other filenames have
  714.    the current working directory prepended.  A new string is
  715.    returned in either case. */
  716. char *
  717. full_pathname (file)
  718.      char *file;
  719. {
  720.   char *disposer;
  721.  
  722.   if (*file == '~')
  723.     file = tilde_expand (file);
  724.   else
  725.     file = savestring (file);
  726.  
  727.   if ((*file == '/') && absolute_pathname (file))
  728.     return (file);
  729.  
  730.   disposer = file;
  731.  
  732.   {
  733.     char *current_dir = xmalloc (2 + MAXPATHLEN + strlen (file));
  734.     int dlen;
  735.     if (getwd (current_dir) == 0)
  736.       {
  737.     report_error (current_dir);
  738.     free (current_dir);
  739.     return ((char *)NULL);
  740.       }
  741.     dlen = strlen (current_dir);
  742.     current_dir[dlen++] = '/';
  743.  
  744.     /* Turn /foo/./bar into /foo/bar. */
  745.     if (file[0] == '.' && file[1] == '/')
  746.       file += 2;
  747.  
  748.     strcpy (current_dir + dlen, file);
  749.     free (disposer);
  750.     return (current_dir);
  751.   }
  752. }
  753.  
  754. #if !defined (HAVE_STRCASECMP)
  755.  
  756. #if !defined (to_upper)
  757. #  define to_upper(c) (islower(c) ? toupper(c) : (c))
  758. #endif /* to_upper */
  759.  
  760. /* Compare at most COUNT characters from string1 to string2.  Case
  761.    doesn't matter. */
  762. int
  763. strnicmp (string1, string2, count)
  764.      char *string1, *string2;
  765.      int count;
  766. {
  767.   register char ch1, ch2;
  768.  
  769.   while (count)
  770.     {
  771.       ch1 = *string1++;
  772.       ch2 = *string2++;
  773.       if (to_upper(ch1) == to_upper(ch2))
  774.     count--;
  775.       else
  776.     break;
  777.     }
  778.   return (count);
  779. }
  780.  
  781. /* strcmp (), but caseless. */
  782. int
  783. stricmp (string1, string2)
  784.      char *string1, *string2;
  785. {
  786.   register char ch1, ch2;
  787.  
  788.   while (*string1 && *string2)
  789.     {
  790.       ch1 = *string1++;
  791.       ch2 = *string2++;
  792.       if (to_upper(ch1) != to_upper(ch2))
  793.     return (1);
  794.     }
  795.   return (*string1 - *string2);
  796. }
  797. #endif /* !HAVE_STRCASECMP */
  798.  
  799. /* Determine if s2 occurs in s1.  If so, return a pointer to the
  800.    match in s1.  The compare is case insensitive. */
  801. char *
  802. strindex (s1, s2)
  803.      char *s1, *s2;
  804. {
  805.   register int i, l = strlen (s2);
  806.   register int len = strlen (s1);
  807.  
  808.   for (i = 0; (len - i) >= l; i++)
  809.     if (strnicmp (s1 + i, s2, l) == 0)
  810.       return (s1 + i);
  811.   return ((char *)NULL);
  812. }
  813.  
  814. /* Set the environment variables $LINES and $COLUMNS in response to
  815.    a window size change. */
  816. void
  817. set_lines_and_columns (lines, cols)
  818.      int lines, cols;
  819. {
  820.   char *val;
  821.  
  822.   val = itos (lines);
  823.   bind_variable ("LINES", val);
  824.   free (val);
  825.  
  826.   val = itos (cols);
  827.   bind_variable ("COLUMNS", val);
  828.   free (val);
  829. }
  830.  
  831. /* A wrapper for bcopy that can be prototyped in general.h */
  832. void
  833. xbcopy (s, d, n)
  834.      char *s, *d;
  835.      int n;
  836. {
  837.   FASTCOPY (s, d, n);
  838. }
  839.  
  840. /* Return a string corresponding to the error number E.  From
  841.    the ANSI C spec. */
  842. #if defined (strerror)
  843. #  undef strerror
  844. #endif
  845.  
  846. #if !defined (HAVE_STRERROR)
  847. char *
  848. strerror (e)
  849.      int e;
  850. {
  851.   extern int sys_nerr;
  852.   extern char *sys_errlist[];
  853.   static char emsg[40];
  854.  
  855.   if (e > 0 && e < sys_nerr)
  856.     return (sys_errlist[e]);
  857.   else
  858.     {
  859.       sprintf (emsg, "Unknown error %d", e);
  860.       return (&emsg[0]);
  861.     }
  862. }
  863. #endif /* HAVE_STRERROR */
  864.  
  865. #if (defined (USG) && !defined (HAVE_TIMEVAL)) || defined (Minix)
  866. #  define TIMEVAL_MISSING
  867. #endif
  868.  
  869. #if !defined (TIMEVAL_MISSING) || defined (HAVE_RESOURCE)
  870. /* Print the contents of a struct timeval * in a standard way. */
  871. void
  872. print_timeval (tvp)
  873.      struct timeval *tvp;
  874. {
  875.   int minutes, seconds_fraction;
  876.   long seconds;
  877.  
  878.   seconds = tvp->tv_sec;
  879.  
  880.   seconds_fraction = tvp->tv_usec % 1000000;
  881.   seconds_fraction = (seconds_fraction * 100) / 1000000;
  882.  
  883.   minutes = seconds / 60;
  884.   seconds %= 60;
  885.  
  886.   printf ("%0dm%0ld.%02ds",  minutes, seconds, seconds_fraction);
  887. }
  888. #endif /* !TIMEVAL_MISSING || HAVE_RESOURCE */
  889.  
  890. /* Print the time defined by a time_t (returned by the `times' and `time'
  891.    system calls) in a standard way.  This is scaled in terms of HZ, which
  892.    is what is returned by the `times' call. */
  893.  
  894. #if !defined (BrainDeath)
  895. #  if !defined (HZ)
  896. #    if defined (USG)
  897. #      define HZ 100        /* From my Sys V.3.2 manual for times(2) */
  898. #    else
  899. #      define HZ 60        /* HZ is always 60 on BSD systems */
  900. #    endif /* USG */
  901. #  endif /* HZ */
  902.  
  903. void
  904. print_time_in_hz (t)
  905.   time_t t;
  906. {
  907.   int minutes, seconds_fraction;
  908.   long seconds;
  909.  
  910.   seconds_fraction = t % HZ;
  911.   seconds_fraction = (seconds_fraction * 100) / HZ;
  912.  
  913.   seconds = t / HZ;
  914.  
  915.   minutes = seconds / 60;
  916.   seconds %= 60;
  917.  
  918.   printf ("%0dm%0ld.%02ds",  minutes, seconds, seconds_fraction);
  919. }
  920. #endif /* BrainDeath */
  921.  
  922. #if !defined (HAVE_DUP2)
  923. /* Replacement for dup2 (), for those systems which either don't have it,
  924.    or supply one with broken behaviour. */
  925. int
  926. dup2 (fd1, fd2)
  927.      int fd1, fd2;
  928. {
  929.   extern int getdtablesize ();
  930.   int saved_errno, r;
  931.  
  932.   /* If FD1 is not a valid file descriptor, then return immediately with
  933.      an error. */
  934.   if (fcntl (fd1, F_GETFL, 0) == -1)
  935.     return (-1);
  936.  
  937.   if (fd2 < 0 || fd2 >= getdtablesize ())
  938.     {
  939.       errno = EBADF;
  940.       return (-1);
  941.     }
  942.  
  943.   if (fd1 == fd2)
  944.     return (0);
  945.  
  946.   saved_errno = errno;
  947.  
  948.   (void) close (fd2);
  949.   r = fcntl (fd1, F_DUPFD, fd2);
  950.  
  951.   if (r >= 0)
  952.     errno = saved_errno;
  953.   else
  954.     if (errno == EINVAL)
  955.       errno = EBADF;
  956.  
  957.   /* Force the new file descriptor to remain open across exec () calls. */
  958.   SET_OPEN_ON_EXEC (fd2);
  959.   return (r);
  960. }
  961. #endif /* !HAVE_DUP2 */
  962.  
  963. /*
  964.  * Return the total number of available file descriptors.
  965.  *
  966.  * On some systems, like 4.2BSD and its descendents, there is a system call
  967.  * that returns the size of the descriptor table: getdtablesize().  There are
  968.  * lots of ways to emulate this on non-BSD systems.
  969.  *
  970.  * On System V.3, this can be obtained via a call to ulimit:
  971.  *    return (ulimit(4, 0L));
  972.  *
  973.  * On other System V systems, NOFILE is defined in /usr/include/sys/param.h
  974.  * (this is what we assume below), so we can simply use it:
  975.  *    return (NOFILE);
  976.  *
  977.  * On POSIX systems, there are specific functions for retrieving various
  978.  * configuration parameters:
  979.  *    return (sysconf(_SC_OPEN_MAX));
  980.  *
  981.  */
  982.  
  983. #if !defined (USG) && !defined (HPUX)
  984. #  define HAVE_GETDTABLESIZE
  985. #endif /* !USG && !HPUX */
  986.  
  987. #if defined (hppa) && (defined (hpux_8) || defined (hpux_9))
  988. #  undef HAVE_GETDTABLESIZE
  989. #endif /* hppa && hpux_8 */
  990.  
  991. #if !defined (HAVE_GETDTABLESIZE)
  992. int
  993. getdtablesize ()
  994. {
  995. #  if defined (_POSIX_VERSION) && defined (_SC_OPEN_MAX)
  996.   return (sysconf(_SC_OPEN_MAX));    /* Posix systems use sysconf */
  997. #  else /* ! (_POSIX_VERSION && _SC_OPEN_MAX) */
  998. #    if defined (USGr3)
  999.   return (ulimit (4, 0L));    /* System V.3 systems use ulimit(4, 0L) */
  1000. #    else /* !USGr3 */
  1001. #      if defined (NOFILE)    /* Other systems use NOFILE */
  1002.   return (NOFILE);
  1003. #      else /* !NOFILE */
  1004.   return (20);            /* XXX - traditional value is 20 */
  1005. #      endif /* !NOFILE */
  1006. #    endif /* !USGr3 */
  1007. #  endif /* ! (_POSIX_VERSION && _SC_OPEN_MAX) */
  1008. }
  1009. #endif /* !HAVE_GETDTABLESIZE */
  1010.  
  1011. #if defined (USG)
  1012.  
  1013. #if !defined (HAVE_BCOPY)
  1014. bcopy (s,d,n) char *d,*s; { FASTCOPY (s, d, n); }
  1015. bzero (s,n) char *s; int n; { memset(s, '\0', n); }
  1016. #endif /* !HAVE_BCOPY */
  1017.  
  1018. #if !defined (HAVE_GETHOSTNAME)
  1019. #include <sys/utsname.h>
  1020. int
  1021. gethostname (name, namelen)
  1022.      char *name;
  1023.      int namelen;
  1024. {
  1025.   int i;
  1026.   struct utsname ut;
  1027.  
  1028.   --namelen;
  1029.  
  1030.   uname (&ut);
  1031.   i = strlen (ut.nodename) + 1;
  1032.   strncpy (name, ut.nodename, i < namelen ? i : namelen);
  1033.   name[namelen] = '\0';
  1034.   return (0);
  1035. }
  1036. #endif /* !HAVE_GETHOSTNAME */
  1037. #endif /* USG */
  1038.  
  1039. #if !defined (HAVE_GETWD)
  1040. char *
  1041. getwd (string)
  1042.      char *string;
  1043. {
  1044.   extern char *getcwd ();
  1045.   char *result;
  1046.  
  1047.   result = getcwd (string, MAXPATHLEN);
  1048.   if (result == NULL)
  1049.     strcpy (string, "getwd: cannot access parent directories");
  1050.   return (result);
  1051. }
  1052. #endif /* !HAVE_GETWD */
  1053.  
  1054. /* A slightly related function.  Get the prettiest name of this
  1055.    directory possible. */
  1056. static char tdir[MAXPATHLEN];
  1057.  
  1058. /* Return a pretty pathname.  If the first part of the pathname is
  1059.    the same as $HOME, then replace that with `~'.  */
  1060. char *
  1061. polite_directory_format (name)
  1062.      char *name;
  1063. {
  1064.   char *home = get_string_value ("HOME");
  1065.   int l = home ? strlen (home) : 0;
  1066.  
  1067.   if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))
  1068.     {
  1069.       strcpy (tdir + 1, name + l);
  1070.       tdir[0] = '~';
  1071.       return (tdir);
  1072.     }
  1073.   else
  1074.     return (name);
  1075. }
  1076.  
  1077. #if defined (NO_READ_RESTART_ON_SIGNAL)
  1078. /* Posix and USG systems do not guarantee to restart read () if it is
  1079.    interrupted by a signal.  We do the read ourselves, and restart it
  1080.    if it returns EINTR. */
  1081. int
  1082. getc_with_restart (stream)
  1083.      FILE *stream;
  1084. {
  1085.   static char localbuf[128];
  1086.   static int local_index = 0, local_bufused = 0;
  1087.  
  1088.   /* Try local buffering to reduce the number of read(2) calls. */
  1089.   if (local_index == local_bufused || local_bufused == 0)
  1090.     {
  1091.       while (1)
  1092.     {
  1093.       local_bufused = read (fileno (stream), localbuf, sizeof(localbuf));
  1094.       if (local_bufused > 0)
  1095.         break;
  1096.       else if (local_bufused == 0 || errno != EINTR)
  1097.         {
  1098.           local_index = 0;
  1099.           return EOF;
  1100.         }
  1101.     }
  1102.       local_index = 0;
  1103.     }
  1104.   return (localbuf[local_index++]);
  1105. }
  1106. #endif /* NO_READ_RESTART_ON_SIGNAL */
  1107.  
  1108. #if defined (USG) || defined (AIX) || (defined (_POSIX_VERSION) && defined (Ultrix))
  1109. /* USG and strict POSIX systems do not have killpg ().  But we use it in
  1110.    jobs.c, nojobs.c and some of the builtins.  This can also be redefined
  1111.    as a macro if necessary. */
  1112. #if !defined (_POSIX_VERSION)
  1113. #  define pid_t int
  1114. #endif /* _POSIX_VERSION */
  1115.  
  1116. int
  1117. killpg (pgrp, sig)
  1118.      pid_t pgrp;
  1119.      int sig;
  1120. {
  1121.   return (kill (-pgrp, sig));
  1122. }
  1123. #endif /* USG  || AIX || (_POSIX_VERSION && Ultrix) */
  1124.  
  1125. /* **************************************************************** */
  1126. /*                                    */
  1127. /*            Tilde Initialization and Expansion            */
  1128. /*                                    */
  1129. /* **************************************************************** */
  1130.  
  1131. /* If tilde_expand hasn't been able to expand the text, perhaps it
  1132.    is a special shell expansion.  This function is installed as the
  1133.    tilde_expansion_failure_hook.  It knows how to expand ~- and ~+. */
  1134. static char *
  1135. bash_tilde_expand (text)
  1136.      char *text;
  1137. {
  1138.   char *result = (char *)NULL;
  1139.  
  1140.   if (!text[1])
  1141.     {
  1142.       if (*text == '+')
  1143.         result = get_string_value ("PWD");
  1144.       else if (*text == '-')
  1145.         result = get_string_value ("OLDPWD");
  1146.     }
  1147.  
  1148.   if (result)
  1149.     result = savestring (result);
  1150.  
  1151.   return (result);
  1152. }
  1153.  
  1154. /* Initialize the tilde expander.  In Bash, we handle `~-' and `~+', as
  1155.    well as handling special tilde prefixes; `:~" and `=~' are indications
  1156.    that we should do tilde expansion. */
  1157. void
  1158. tilde_initialize ()
  1159. {
  1160.   static int times_called = 0;
  1161.  
  1162.   /* Tell the tilde expander that we want a crack if it fails. */
  1163.   tilde_expansion_failure_hook = (CPFunction *)bash_tilde_expand;
  1164.  
  1165.   /* Tell the tilde expander about special strings which start a tilde
  1166.      expansion, and the special strings that end one.  Only do this once.
  1167.      tilde_initialize () is called from within bashline_reinitialize (). */
  1168.   if (times_called == 0)
  1169.     {
  1170.       tilde_additional_prefixes = (char **)xmalloc (3 * sizeof (char *));
  1171.       tilde_additional_prefixes[0] = "=~";
  1172.       tilde_additional_prefixes[1] = ":~";
  1173.       tilde_additional_prefixes[2] = (char *)NULL;
  1174.  
  1175.       tilde_additional_suffixes = (char **)xmalloc (3 * sizeof (char *));
  1176.       tilde_additional_suffixes[0] = ":";
  1177.       tilde_additional_suffixes[1] = "=~";
  1178.       tilde_additional_suffixes[2] = (char *)NULL;
  1179.     }
  1180.   times_called++;
  1181. }
  1182.  
  1183. #if defined (_POSIX_VERSION)
  1184.  
  1185. #if !defined (SA_INTERRUPT)
  1186. #  define SA_INTERRUPT 0
  1187. #endif
  1188.  
  1189. #if !defined (SA_RESTART)
  1190. #  define SA_RESTART 0
  1191. #endif
  1192.  
  1193. SigHandler *
  1194. set_signal_handler (sig, handler)
  1195.      int sig;
  1196.      SigHandler *handler;
  1197. {
  1198.   struct sigaction act, oact;
  1199.  
  1200.   act.sa_handler = handler;
  1201.   act.sa_flags = 0;
  1202. #if 0
  1203.   if (sig == SIGALRM)
  1204.     act.sa_flags |= SA_INTERRUPT;    /* XXX */
  1205.   else
  1206.     act.sa_flags |= SA_RESTART;        /* XXX */
  1207. #endif
  1208.   sigemptyset (&act.sa_mask);
  1209.   sigemptyset (&oact.sa_mask);
  1210.   sigaction (sig, &act, &oact);
  1211.   return (oact.sa_handler);
  1212. }
  1213. #endif /* _POSIX_VERSION */
  1214.